﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace League
{
    public class League
    {
        private List<Team> teams = new List<Team>(); // 球队列表

        // 查找球队
        public Team GetTeamByName(string name)
        {
            return teams.FirstOrDefault(t => t.Name == name);
        }

        // 添加球队
        public void AddTeam(Team team)
        {
            teams.Add(team);
        }

        // 更新比赛结果
        public void UpdateMatch(string homeTeamName, string awayTeamName, int homeScore, int awayScore)
        {
            var homeTeam = GetTeamByName(homeTeamName);
            var awayTeam = GetTeamByName(awayTeamName);

            // 更新比赛场数
            homeTeam.MatchesPlayed++;
            awayTeam.MatchesPlayed++;

            // 更新进球和失球
            homeTeam.GoalsFor += homeScore;
            homeTeam.GoalsAgainst += awayScore;
            awayTeam.GoalsFor += awayScore;
            awayTeam.GoalsAgainst += homeScore;

            // 判断比赛结果并更新积分
            if (homeScore > awayScore) // 主队胜
            {
                homeTeam.Wins++;
                awayTeam.Losses++;
                homeTeam.Points += 3;
            }
            else if (homeScore == awayScore) // 平局
            {
                homeTeam.Draws++;
                awayTeam.Draws++;
                homeTeam.Points += 1;
                awayTeam.Points += 1;
            }
            else // 客队胜
            {
                awayTeam.Wins++;
                homeTeam.Losses++;
                awayTeam.Points += 3;
            }
        }

        // 排名球队并输出最新积分表
        public void PrintRankings()
        {
            Console.WriteLine($"{"队名",-15} {"赛",4} {"胜",4} {"平",4} {"负",4} {"进球",4} {"失球",4} {"净胜球",6} {"积分",4}");

            var sortedTeams = teams.OrderByDescending(t => t.Points)
                                   .ThenByDescending(t => t.GoalDifference)
                                   .ThenByDescending(t => t.GoalsFor)
                                   .ToList();

            foreach (var team in sortedTeams)
            {
                team.PrintInfo();
            }
        }
    }
}
